package com.jeesuite.admin.component;

import java.util.List;

import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jeesuite.admin.constants.UserType;
import com.jeesuite.admin.dao.entity.BusinessGroupEntity;
import com.jeesuite.admin.dao.entity.UserEntity;
import com.jeesuite.admin.dao.mapper.BusinessGroupEntityMapper;
import com.jeesuite.admin.dao.mapper.UserEntityMapper;
import com.jeesuite.admin.model.LoginUserInfo;
import com.jeesuite.admin.util.SecurityUtil;
import com.mendmix.common.MendmixBaseException;
import com.mendmix.common.model.AuthUser;
import com.mendmix.common.util.FormatValidateUtils;
import com.mendmix.security.SecurityDecisionProvider;
import com.mendmix.security.exception.UserPasswordWrongException;
import com.mendmix.security.model.ApiPermission;
import com.mendmix.spring.InstanceFactory;

@Component
public class DefaultSecurityDecisionProvider extends SecurityDecisionProvider {


	private @Autowired UserEntityMapper userMapper;
	
	@Override
	public boolean isServletType() {
		return true;
	}

	@Override
	public AuthUser validateUser(String name, String password) throws MendmixBaseException {
		UserEntity userEntity;
		if (FormatValidateUtils.isMobile(name)) {
			userEntity = userMapper.findByMobile(name);
		} else if (FormatValidateUtils.isEmail(name)) {
			userEntity = userMapper.findByEmail(name);
		} else {
			userEntity = userMapper.findByName(name);
		}

		if (userEntity == null || !BCrypt.checkpw(password, userEntity.getPassword())) {
			throw new UserPasswordWrongException();
		}

		LoginUserInfo userInfo = new LoginUserInfo();
		userInfo.setId(userEntity.getId().toString());
		userInfo.setName(userEntity.getName());
		userInfo.setType(userEntity.getType());
		userInfo.setGroupId(userEntity.getGroupId());
		if (!userInfo.isSuperAdmin()) {
			if (!userEntity.getEnabled()) {
				throw new MendmixBaseException(1001, "该账号已停用");
			}
			// 加载权限
			SecurityUtil.initPermssionDatas(userInfo);
		}

		if (userEntity.getGroupId() != null) {
			BusinessGroupEntity groupEntity = InstanceFactory.getInstance(BusinessGroupEntityMapper.class)
					.selectByPrimaryKey(userEntity.getGroupId());
			if (groupEntity != null) {
				userInfo.setGroupMaster(userEntity.getId().equals(groupEntity.getMasterUid()));
				if (userInfo.isGroupMaster()) {
					userInfo.setGroupId(groupEntity.getId());
					userInfo.setType(UserType.groupAdmin.name());
				}
			}
		}

		return userInfo;
	}

	@Override
	public List<ApiPermission> getAllApiPermissions() {
		return null;
	}

	@Override
	public String error401Page() {
		return null;
	}

	@Override
	public String error403Page() {
		return null;
	}
	
	

	@Override
	public boolean apiAuthzEnabled() {
		return false;
	}

	@Override
	public List<ApiPermission> getUserApiPermissions(String userId) {
		return null;
	}

}